<template>
	<view class="content bgGray pb10">
		<view class="bgWhite flex-r jsb p16" style="border-bottom: 1rpx solid #eee">
			<view>商户名称</view>
			<view class="gray f1">
				<input type="text" class="textRight" v-model="form.tMerchantname" style="width: 100%" />
			</view>
		</view>
		<view class="bgWhite ver-c p16">
			<view class="mb16">营业执照</view>
			<view class="flex-r upload-img wrap">
				<view v-for="(image, imgIndex) in fileList" :key="imgIndex">
					<view class="uni-uploader__file">
						<image
							class="uni-uploader__img"
							:src="image.ip + image.url"
							:data-src="image.url"
							@click="preview(image.ip + image.url)"
							@longtap="onDeleteClick(imgIndex, index)"
						></image>
					</view>
				</view>
				<image src="/static/img/add@2x.png" class="img" @tap="onGetImgClick()"></image>
			</view>
		</view>
		<!-- 门面照片 -->
		<view class="bgWhite p16" style="border-bottom: 1rpx solid #eee">
			<view class="mb16">门面照片</view>
			<view class="gray f1">
				<view v-if="!shopFrontImage" @tap="onGetShopFrontImgClick()">
					<image src="/static/img/add@2x.png" class="img"></image>
				</view>
				<view
					v-else
					class="uni-uploader__file"
					@tap="preview(shopFrontImage.ip + shopFrontImage.url)"
					@longtap="onDeleteShopFrontImgClick()"
				>
					<image class="uni-uploader__img" :src="shopFrontImage.ip + shopFrontImage.url"></image>
				</view>
			</view>
			<view class="gray fs13 mt10">提示：如需更换删除图片，可长按已上传的图片删除</view>
		</view>

		<view class="bgWhite mt6 flex-c jsb p16" style="border-bottom: 1rpx solid #eee">
			<view>商铺介绍</view>
			<view class="gray mt16 f1">
				<textarea
					class="fs13"
					style="
						background: #eee;
						height: 140rpx;
						width: 100%;
						padding: 20rpx;
						box-sizing: border-box;
						border-radius: 20rpx;
					"
					v-model="form.tMerchantintroduce"
				/>
			</view>
		</view>
		<view class="bgWhite mt6 flex-r jsb p16" style="border-bottom: 1rpx solid #eee">
			<view>联系人</view>
			<view class="gray f1">
				<input type="text" class="textRight" v-model="form.tMerchantcontacts" style="width: 100%" />
			</view>
		</view>
		<view class="bgWhite flex-r jsb p16" style="border-bottom: 1rpx solid #eee">
			<view>电话</view>
			<view class="gray f1">
				<input type="text" class="textRight" v-model="form.tMerchantphone" style="width: 100%" />
			</view>
		</view>
		<view class="bgWhite flex-r jsb p16" style="border-bottom: 1rpx solid #eee">
			<view>微信号</view>
			<view class="gray f1">
				<input type="text" class="textRight" v-model="form.tMerchantwechat" style="width: 100%" />
			</view>
		</view>
		<view class="bgWhite p16" style="border-bottom: 1rpx solid #eee">
			<view class="flex-r ver-c jsb">
				<view>商户地址</view>
				<view class="fs13 gray" @click="resetLocation">重新定位</view>
			</view>
			<view class="gray f1 mt16" style="width: 100%">
				<textarea
					class="fs13"
					style="
						background: #eee;
						height: 140rpx;
						width: 100%;
						padding: 20rpx;
						box-sizing: border-box;
						border-radius: 20rpx;
					"
					v-model="form.tMerchantaddress"
					disabled
				/>
			</view>
			<view class="fs13 gray mt10">
				提示：店铺地址授权后自动定位，请确定店铺位置后定位，这将直接影响用户导航到店位置！
			</view>
		</view>
		<view class="bgWhite p16" style="border-bottom: 1rpx solid #eee">
			<view>地址门牌号</view>
			<view class="gray f1 mt16" style="width: 100%">
				<textarea
					class="fs13"
					style="
						background: #eee;
						height: 140rpx;
						width: 100%;
						padding: 20rpx;
						box-sizing: border-box;
						border-radius: 20rpx;
					"
					v-model="form.tSpecificaddress"
					placeholder="请输入门牌号"
				/>
			</view>
		</view>

		<view class="savebtn textCenter mb16 white" @tap="save()">保存</view>
	</view>
</template>

<script>
import Utils from '@/utils/utils.js'
import { IP, ImgIP, throttle } from '@/utils/comm.js'
import { editMerchantInfo, getMerchantInfo } from '@/api/mine.js'
import amapFile from '@/utils/map/amap-wx.130.js' // 高德
//import QQMapWX from '@/utils/map/qqmap-wx-jssdk.min.js'
export default {
	data() {
		return {
			fileList: [], //上传图片
			shopFrontImage: null, // 门面照片
			token: '',
			form: {
				tMerchantid: '',
				tMerchantname: '',
				tMerchantcontacts: '',
				tMerchantphone: '',
				tMerchantaddress: '',
				tMerchantintroduce: '', //商铺介绍
				tMerchantwechat: '',
				tSpecificaddress: '', //门牌号地址
				tMerchantlicenseimg: '', //图片
				tLongitude: '',
				tLatitude: ''
			}
		}
	},
	onReady() {
		this.getAuthorize()
			.then(() => {
				//   同意后获取
				this.getLocationInfo()
			})
			.catch(() => {
				//   不同意给出弹框，再次确认
				this.openConfirm()
					.then(() => {
						this.getLocationInfo()
					})
					.catch(() => {
						this.rejectGetLocation()
					})
			})
	},
	onLoad(option) {
		console.log('?', option.tMerchantid)
		this.form.tMerchantid = option.tMerchantid
		let token = Utils.getToken()
		//console.log(token)
		this.token = token
		//获取商家信息
		this.getMerchantInfo(option.tMerchantid)
	},
	onShow() {},
	methods: {
		//   初次位置授权
		getAuthorize() {
			return new Promise((resolve, reject) => {
				uni.authorize({
					scope: 'scope.userLocation',
					success: () => {
						resolve() // 允许授权
					},
					fail: () => {
						reject() // 拒绝授权
					}
				})
			})
		},
		// 确认授权，获取用户位置
		async getLocationInfo() {
			const that = this
			//位置信息默认数据
			// let location = {
			// 	longitude: 0,
			// 	latitude: 0,
			// 	province: '',
			// 	city: '',
			// 	area: '',
			// 	street: '',
			// 	address: ''
			// }
			uni.getLocation({
				type: 'gcj02',
				success: function (res) {
					// 暂时
					console.log(res)
					// location.longitude = res.longitude //118.787575;
					// location.latitude = res.latitude //32.05024;
					that.form.tLongitude = res.longitude
					that.form.tLatitude = res.latitude
					console.log('获取当前的用户经度', that.form.tLongitude)
					console.log('获取当前的用户纬度', that.form.tLatitude)
					var long = 0
					var lat = 0
					//小数点保留六位  经度
					if (that.form.tLongitude.toString().indexOf('.') > 0) {
						const longlatsplit = that.form.tLongitude.toString().split('.')
						if (longlatsplit.length >= 2) {
							long =
								parseFloat(longlatsplit[0] === '' ? 0 : longlatsplit[0]) +
								parseFloat('.' + longlatsplit[1].slice(0, 6))
						}
					}
					if (that.form.tLatitude.toString().indexOf('.') > 0) {
						const longlatsplit1 = that.form.tLatitude.toString().split('.')
						if (longlatsplit1.length >= 2) {
							lat =
								parseFloat(longlatsplit1[0] === '' ? 0 : longlatsplit1[0]) +
								parseFloat('.' + longlatsplit1[1].slice(0, 6))
						}
					}
					console.log('经度=>', long, '纬度=>', lat)
					// this.distance(that.latitude,that.longitude);

					// 高德地图Api 经纬度转地址
					const myAmapFun = new amapFile.AMapWX({
						key: '035dcb4d7445f66af24a23263863533c'
					})
					myAmapFun.getRegeo({
						location: `${long},${lat}`,
						success: (res) => {
							console.log('==>', res, res[0].regeocodeData.formatted_address)
							//location.address = res[0].regeocodeData.formatted_address
							that.form.tMerchantaddress = res[0].regeocodeData.formatted_address
							//resolve(location)
						}
					})

					// 腾讯地图Api
					// const qqmapsdk = new QQMapWX({
					// 	key: 'T6SBZ-CJV3J-J2DF3-XQ737-MFLX2-D5BAC'
					// })
					// qqmapsdk.reverseGeocoder({
					// 	location: {
					// 		latitude: lat,
					// 		longitude: long
					// 	},
					// 	sig: '0zdE6y07RhtVKnfS1VTVeTuQaUqsi5dr', // 签名校验
					// 	success(response) {
					// 		let info = response.result
					// 		console.log('地址=>：', info)
					// 		that.form.tMerchantaddress = info.address
					// 	}
					// })
				}
			})
		},
		// 拒绝授权后，弹框提示是否手动打开位置授权
		openConfirm() {
			return new Promise((resolve, reject) => {
				uni.showModal({
					title: '请求授权当前位置',
					content: '我们需要获取地理位置信息，为您推荐附近的商品',
					success: (res) => {
						if (res.confirm) {
							uni.openSetting().then((res) => {
								if (res[1].authSetting['scope.userLocation'] === true) {
									resolve() // 打开地图权限设置
								} else {
									reject()
								}
							})
						} else if (res.cancel) {
							reject()
						}
					}
				})
			})
		},

		// 彻底拒绝位置获取
		rejectGetLocation() {
			Utils.toast('你拒绝了授权，无法定位当前位置')
		},
		resetLocation() {
			this.getLocationInfo()
		},
		getMerchantInfo(tMerchantid) {
			getMerchantInfo(tMerchantid).then((res) => {
				console.log(res)
				this.form = res.data
				if (res.data.tMerchantlicenseimg) {
					this.fileList = res.data.tMerchantlicenseimg.split(',').map((item) => {
						return {
							url: item,
							ip: ImgIP
						}
					})
					console.log('fileList->', this.fileList)
				}
				if (res.data.tMerchantimg) {
					this.shopFrontImage = {
						url: res.data.tMerchantimg,
						ip: ImgIP
					}
				}
			})
		},
		save: throttle(function (e) {
			//console.log(params)
			this.form.tMerchantlicenseimg =
				this.fileList.length > 0 ? this.fileList.map((item) => item.url).join(',') : ''
			console.log(this.form.tMerchantlicenseimg)
			this.form.tMerchantimg = this.shopFrontImage ? this.shopFrontImage.url : ''
			const regex = /^[1][3-9][0-9]{9}$/
			if (this.form.tMerchantname == '') return Utils.toast('商户名不能为空')
			if (this.form.tMerchantintroduce == '') return Utils.toast('商铺介绍不能为空')
			if (this.form.tMerchantcontacts == '') return Utils.toast('联系人不能为空')
			if (!regex.test(this.form.tMerchantphone)) return Utils.toast('请输入正确的手机号')
			if (this.form.tMerchantwechat == '') return Utils.toast('微信号不能为空')
			if (this.form.tMerchantaddress == '') return Utils.toast('地址不能为空')
			if (this.form.tSpecificaddress == '') return Utils.toast('地址门牌号不能为空')
			if (this.form.tMerchantlicenseimg == '') return Utils.toast('营业执照不能为空')
			if (this.form.tMerchantimg == '') return Utils.toast('门店照片不能为空')
			let params = {
				...this.form
			}
			console.log('tijiao', params)
			editMerchantInfo(params).then((res) => {
				console.log(res)
				Utils.toast(res.msg)
				setTimeout(() => {
					uni.navigateBack()
				}, 1000)
			})
		}),
		onGetImgClick() {
			const that = this
			uni.chooseImage({
				count: 9, // 最多可以选择的图片张数，默认9
				sizeType: ['original', 'compressed'], //original 原图，compressed 压缩图，默认二者都有
				sourceType: ['album', 'camera'], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
				success: function (res) {
					if (!that.fileList) {
						that.fileList = []
					}
					const len = that.fileList.length
					if (len >= 9) {
						uni.showToast({
							title: '图片最多上传9张'
						})
					} else {
						for (let i = 0; i < 9 - len; i++) {
							if (res.tempFilePaths[i]) {
								that.uploadFilePromise(res.tempFilePaths[i])
							}
						}
					}
				}
			})
		},
		//上传图片
		uploadFilePromise(url) {
			//var tempFile = [
			//{
			//name: 'file',
			//uri: url
			//}
			//]
			//console.log('???-->', url)
			return new Promise((resolve, reject) => {
				//console.log('1111')
				let a = uni.uploadFile({
					url: IP + 'common/upload',
					filePath: url, //小程序
					//files: tempFile,	//app
					header: {
						Authorization: 'Bearer ' + this.token
					},
					name: 'file',
					success: (res) => {
						//console.log('上传成功', res)
						let imgObj = res.data
						let obj = JSON.parse(imgObj)
						if (obj.url) {
							if (!this.fileList) {
								this.fileList = []
							}
							this.fileList.push({ ip: ImgIP, url: obj.fileName })
							console.log(this.fileList)
							this.fileList = Object.assign([], this.fileList)
						} else {
							uni.$u.toast(obj.msg)
						}

						//隐藏上传中
						setTimeout(() => {
							resolve(res.data.data)
						}, 1000)
					},
					fail: (err) => {
						console.log(err)
					}
				})
			})
		},
		// 预览图片
		preview(img) {
			console.log('预览')
			// 新建一个存放预览图片的空数组
			var imgArr = []
			imgArr.push(img)
			uni.previewImage({
				urls: imgArr,
				current: imgArr[0],
				longPressActions: {}
			})
		},
		// 长按删除图片
		onDeleteClick(imgIndex, index) {
			// this.imageList.splice(index, 1)
			uni.showModal({
				title: '删除图片',
				content: '确定删除图片?',
				success: (res) => {
					if (res.confirm) {
						// 删除图片 将数据置空
						this.fileList.splice(imgIndex, 1)
					} else if (res.cancel) {
						console.log('用户点击取消')
					}
					this.fileList = Object.assign([], this.fileList)
				}
			})
		},
		onDeleteShopFrontImgClick() {
			uni.showModal({
				title: '删除图片',
				content: '确定删除这张门面照片?',
				success: (res) => {
					if (res.confirm) {
						// 删除门面照片
						this.shopFrontImage = null
						this.form.tMerchantimg = '' // 同时清除表单中的数据
					} else if (res.cancel) {
						console.log('用户点击取消')
					}
				}
			})
		},
		// 门面照片点击上传
		onGetShopFrontImgClick() {
			const that = this
			uni.chooseImage({
				count: 1,
				sizeType: ['original', 'compressed'],
				sourceType: ['album', 'camera'],
				success: function (res) {
					if (res.tempFilePaths.length > 0) {
						that.uploadShopFrontFilePromise(res.tempFilePaths[0])
					}
				}
			})
		},
		// 上传门面照片
		uploadShopFrontFilePromise(url) {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: IP + 'common/upload',
					filePath: url,
					header: {
						Authorization: 'Bearer ' + this.token
					},
					name: 'file',
					success: (res) => {
						let imgObj = res.data
						let obj = JSON.parse(imgObj)
						if (obj.url) {
							this.shopFrontImage = { ip: ImgIP, url: obj.fileName }
							this.form.tMerchantimg = obj.fileName // 设置到form中
						} else {
							uni.$u.toast(obj.msg)
						}
						resolve(res.data.data)
					},
					fail: (err) => {
						console.log(err)
					}
				})
			})
		}
	}
}
</script>

<style lang="stylus" scoped>
.content
	min-height 100%
.mt6
	margin-top 12rpx
.savebtn
	margin 40rpx 32rpx 40rpx
	border-radius 50rpx
	background #c40414
	line-height 90rpx
.img
	padding 60rpx 50rpx
	background #f5f5f5
	border-radius 14rpx
	width 50rpx
	height 40rpx
.uni-uploader__img
	width 150rpx
	height 150rpx
	border-radius(14rpx)
	margin 5rpx
</style>
